import React from 'react'
import Control from '../components/Control'
import BoardArea from '../components/BoardArea'
import {deepCopy} from "../utils/func";
import {BLACK_CHESS, WHITE_CHESS} from "../constants/checkerboard";
import isSuccess from "../utils/five-in-a-row-success";
import {Modal} from "antd";

export default class Game extends React.Component {
    constructor(props) {
        super(props);
        const checkerboard = new Array(15).fill(new Array(15).fill(0));
        this.state = {
            checkerboard,
            // 初始时是黑棋
            isBlack: true,
            isFinish: false
        };
        this.records = [];
    }


    handleColClick(row, col) {
        const state = deepCopy(this.state);
        if (state.isFinish) {
            return;
        }
        state.checkerboard[row][col] = state.isBlack ? BLACK_CHESS : WHITE_CHESS;
        // 每次落子之后才有可能触发胜利，所以我们可以在落子之后去判断是否胜利
        if (isSuccess(state.checkerboard, row, col)) {
            // 代表获胜了
            state.isFinish = true;
            Modal.success({
                content: `恭喜${state.isBlack ? '黑棋' : '白棋'}获取了胜利，请再开一把吧`
            })
        }
        this.records.push(this.state);
        this.setState({
            checkerboard: state.checkerboard,
            isBlack: !state.isBlack,
            isFinish: state.isFinish
        })
    }

    handleReset() {
        const checkerboard = new Array(15).fill(new Array(15).fill(0));
        this.setState({
            checkerboard,
            // 初始时是黑棋
            isBlack: true,
            isFinish: false
        });
        this.records = [];
    }

    // 悔棋处理
    handleRegret(){
        const state = deepCopy(this.records.pop());
        this.setState(state)
    }

    render() {
        const height = window.innerHeight;
        return (
            <div className="Game-container" style={{minHeight: height}}>
                <Control onRegret={this.handleRegret.bind(this)} onReset={this.handleReset.bind(this)} />
                <BoardArea checkerboard={this.state.checkerboard} onColClick={this.handleColClick.bind(this)} />
            </div>
        );
    }
}
// expect default Game;
